
import re
from copy import deepcopy

from db import Session, Ele, json
import demjson

from test00 import isDrink

if __name__=="__main__":

    session = Session()
    shops = session.query(Ele).all()


    with open("text111.txt", "w", encoding="utf-8") as file:
        for index,shop in list(enumerate(shops)):
            shopName = shop.shop
            print(shopName + "计算满减 -- " + str(index + 1))
            menu = shop.contact
            menu = demjson.decode(menu)
            activity = None
            if '满' in shop.detail and '减' in shop.detail:
                activity = demjson.decode(shop.detail)
            activities = None
            if activity :
                activities = activity[0].split("，")
            if not activities:
                continue
            activity = []
            for act in activities:
                res = re.search(r"满\d+减\d+",act)
                if res:
                    allPrice = act.find("满")
                    reducePrice = act.find("减")
                    allPrice = act[allPrice+1:reducePrice]
                    reducePrice = act[reducePrice+1:]
                    activity.append((int(allPrice),int(reducePrice)))
            foods = shop.contact
            foods = demjson.decode(foods)
            for i in range(len(foods)):
                for j in range(i+1,len(foods)):
                    if foods[i].get("price") > foods[j].get("price"):
                        temp = deepcopy(foods[i])
                        foods[i] = deepcopy(foods[j])
                        foods[j] = temp
            plan = {}
            actNum = 0
            for act in activity:
                allPrice = act[0]
                if actNum >= 1:
                    break
                if allPrice <=5 :
                    continue
                else:
                    actNum += 1

                actPlan = []
                i = 0
                j = len(foods) - 1

                tempMethods = {}
                tempPrice = 0
                allPackingFee = 0
                iChange = False
                jChange = False
                while i < j:

                    currentIPrice = foods[i].get("price")
                    packingIFee = foods[i].get("food_packing_fee")
                    if packingIFee == 0:
                        i += 1
                        continue
                    currentJPrice = foods[j].get("price")
                    packingJFee = foods[j].get("food_packing_fee")
                    if not iChange and not jChange and currentJPrice + packingJFee + tempPrice >= allPrice:
                        tempMethods[foods[j].get("food_name")] = currentJPrice
                        allPackingFee += packingJFee
                        tempPrice += currentJPrice
                        tempPrice += packingJFee
                        j -= 1
                        jChange = True
                        iChange = False

                    elif not iChange and not jChange and currentJPrice + packingJFee + tempPrice < allPrice:
                        tempMethods[foods[j].get("food_name")] = currentJPrice
                        allPackingFee += packingJFee
                        tempPrice += currentJPrice
                        tempPrice += packingJFee
                        i += 1
                        jChange = False
                        iChange = True

                    elif iChange and tempPrice + currentIPrice + packingIFee >= allPrice:
                        if not foods[i].get("food_name") in tempMethods.keys():
                            if i - 1 >= 0:
                                if isDrink(foods[i - 1].get("food_name")) and isDrink(foods[i].get("food_name")) and abs(foods[i - 1].get("price") - foods[i - 1].get("price")) <= 1:
                                    i += 1
                                    iChange = True
                                    jChange = False
                                else:
                                    tempMethods[foods[i].get("food_name")] = currentIPrice
                                    allPackingFee += packingIFee
                                    tempPrice += currentIPrice
                                    tempPrice += packingIFee
                                    j -= 1
                                    jChange = True
                                    iChange = False
                        else:
                            i += 1
                            iChange = True
                            jChange = False


                    elif jChange and tempPrice + currentJPrice + packingJFee >= allPrice:
                        if not foods[j].get("food_name") in tempMethods.keys():
                            tempMethods[foods[j].get("food_name")] = currentJPrice
                            allPackingFee += packingJFee
                            tempPrice += currentJPrice
                            tempPrice += packingJFee
                        j -= 1
                        jChange = True
                        iChange = False

                    elif iChange and tempPrice + currentIPrice + packingIFee < allPrice:
                        if not foods[i].get("food_name") in tempMethods.keys():
                            if i - 1 >= 0:
                                if isDrink(foods[i - 1].get("food_name")) and isDrink(foods[i].get("food_name")) and abs(foods[i - 1].get("price") - foods[i - 1].get("price")) <= 1:
                                    i += 1
                                    iChange = True
                                    jChange = False
                                else:
                                    tempMethods[foods[i].get("food_name")] = currentIPrice
                                    allPackingFee += packingIFee
                                    tempPrice += currentIPrice
                                    tempPrice += packingIFee
                                    i += 1
                                    iChange = True
                                    jChange = False
                        else:
                            i += 1
                            iChange = True
                            jChange = False

                    elif jChange and tempPrice + currentJPrice + packingJFee < allPrice:
                        if not foods[j].get("food_name") in tempMethods.keys():
                            tempMethods[foods[j].get("food_name")] = currentJPrice
                            allPackingFee += packingJFee
                            tempPrice += currentJPrice
                            tempPrice += packingJFee
                            i += 1
                            jChange = False
                            iChange = True
                        else:
                            j -= 1
                            jChange = True
                            iChange = False


                    if tempPrice >= allPrice:
                        tempMethods["packingPrice"] = allPackingFee
                        tempMethods["totalPrice"] = tempPrice
                        actPlan.append(tempMethods)
                        tempMethods = {}
                        tempPrice = 0
                        allPackingFee = 0

                for m in range(len(actPlan)):
                    for n in range(m + 1, len(actPlan)):
                        if actPlan[m].get("totalPrice") > actPlan[n].get("totalPrice"):
                            temp = deepcopy(actPlan[m])
                            actPlan[m] = deepcopy(actPlan[n])
                            actPlan[n] = temp

                way = "满{}减{}".format(act[0],act[1])
                plan[way] = actPlan
            session.close()


            file.write("*" + shopName + "==========================\n")
            s = 0
            for k,v in plan.items():
                file.write("\t[" + k + "]\n")
                newUserReducePrice = 0
                acts = demjson.decode(shop.detail)
                for act in acts:
                    if "本店新用户立减" in act:
                        newUserReducePrice = float(re.findall(r'\d+', act)[0])
                if v and  v[0].get("totalPrice") - activity[s][1] - newUserReducePrice <= 20:
                    if v:
                        for t in range(len(v)):
                            if t <= 4:
                                file.write("\t\t方案" + str(t + 1) + ":\n")
                                file.write("\t\t\t")

                                p = 0
                                for key,value in v[t].items():
                                    if p < len(v[t]) - 2:
                                        file.write(key + ":" +str(value) + "  " )
                                    else:
                                        if p == len(v[t]) - 1:
                                            file.write("\n")
                                            file.write("\t\t\t包装费:" + str(round(v[t].get("packingPrice"), 1)) + "  ---  ")
                                            file.write("总价:" + str(round(v[t].get("totalPrice"), 1)) + "\n")

                                            if not newUserReducePrice == 0:
                                                file.write("\t\t\t门店新用户立减:" + str(newUserReducePrice) + "\n")
                                            file.write("\t\t\t满减价:" +
                                                       str(round(v[t].get("totalPrice") - activity[s][1] - newUserReducePrice, 1))
                                                       )
                                            if v[t].get("totalPrice") - activity[s][1] - newUserReducePrice < 10:
                                                file.write("    ****最终价小于10元****\n")
                                            else:
                                                file.write("\n")
                                    p += 1
                        file.write("\n")
                    else:
                        file.write("\t\t该店没有满减优惠\n")
                else:
                    file.write("\t\t暂无合适的满减方案\n")
                s += 1

        file.close()


    f = open("text111.txt", "r", encoding="utf-8")
    lines = f.readlines()
    f.close()

    f = open("text111.txt", "w", encoding="utf-8")
    i = 0
    while i <= len(lines) - 1:

        if i + 2 <= len(lines) - 1 and '暂无合适的满减方案' in lines[i + 2]:
            i += 3
        else:
            f.write(lines[i])
            i += 1

    f.close()


